<!--
 * @Author: Bennent_G
 * @Date: 2024-12-23 16:14:13
 * @LastEditTime: 2025-03-27 19:50:20
 * @Description:
-->
<template>
	<div class="dept-container">
		<div class="dept-tree page-header-container">
			<el-button type="primary" size="small" @click="openModal('add', 0)">新增部门</el-button>
			<el-divider style="margin: 8px 0;"></el-divider>
			<el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick">
				<template #default="{ node, data }">
					<div class="custom-tree-node">
						<span>{{ node.label }}</span>
						<div>
							<el-button type="primary" link @click="openModal('add', 1)">
								新增
							</el-button>
							<el-button style="margin-left: 4px" type="danger" link @click="remove(node, data)">
								删除
							</el-button>
						</div>
					</div>
				</template>
			</el-tree>
		</div>
		<div class="dept-content">
			<DeptUserList :deptId="selectDeptId" />
		</div>
	</div>
	<!--  -->
	<DeptFormModal v-model="modalVisible" :id="currentId" :treeData="treeData" :title="isEdit ? '编辑部门' : '新增部门'" />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { fetchDeptTree } from '@/apis/admin/setting';
import DeptUserList from "@/components/admin/systems/dept/DeptUserList.vue";
import DeptFormModal from "@/components/admin/systems/dept/DeptFormModal.vue";

interface Tree {
	label: string
	children?: Tree[]
}
const handleNodeClick = (data: Tree) => {
	console.log(data);
};
const defaultProps = {
	children: 'children',
	label: 'label',
};
const data: Tree[] = [
	{
		label: '部门1',
		children: [
			{
				label: '部门1-1',
				children: [
					{
						label: '部门e 1-1-1',
					},
				],
			},
		],
	},
	{
		label: '部门2',
		children: [
			{
				label: '部门2-1',
				children: [
					{
						label: '部门e 2-1-1',
					},
				],
			},
			{
				label: '部门2-2',
				children: [
					{
						label: '部门e 2-2-1',
					},
				],
			},
		],
	},
];

const treeData = ref<typeof TreeProps['treeData']>([]);
const getDeptTree = () => {
	fetchDeptTree<typeof TreeProps['treeData']>().then((res) => {
		treeData.value = res.data;
	});
};
onMounted(() => {
	getDeptTree();
});

const selectDeptId = ref<string | number>('');
const handleNodeSelect = (selectedKeys: string[]) => {
	selectDeptId.value = selectedKeys[0];
};

// modal
const modalVisible = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const currentId = ref<number | string>(0);
const openModal = (type: string, id: number | string) => {
	isEdit.value = type === 'edit';
	modalVisible.value = true;
	currentId.value = id;
};

</script>

<style scoped lang="scss">
.dept-container {
	display: grid;
	grid-template-columns: minmax(320px, 1fr) 4fr;
	gap: 16px;
	height: 100%;

	.dept-tree {
		:deep(.el-tree) {
			.custom-tree-node {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}
	}
}
</style>
